<?php
	session_start();
	if(!isset($_SESSION["jara_admin"])) {
		header("Location: ../login.php");
		exit;
	}
	if($_SESSION["jara_permissions"][3] == 0) {	
		header("Location: error.php");
		exit;
	}
	require_once("../include/templating_fns.php");
	require_once("../include/db_fns.php");
	jara_page_start("Upload - Administrator CP");
	$num_users = $result->num_rows;
?>
	<h3>Upload a File</h3>
	<form enctype="multipart/form-data" action="upload.php" method="post">
		<input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
		<input name="userfile" type="file" /><br />
		<input type="submit" value="Upload" />
	</form>
<?php
	if(is_writable("./../uploads/")) {
		if($_FILES["userfile"]["size"] > 0) {
			$ext = strtolower(end(explode(".", basename($_FILES["userfile"]["name"]))));
			if($ext == "php" || $ext == "pl" || $ext == "exe" || $ext == "sh") {
				echo "<p>You're trying to upload an extension that's not allowed. Please upload it inside a container such as a compressed archive.</p>";
			}
			else {
				if($_FILES["userfile"]["error"] == 0) {
					$filename = $_SESSION["jara_admin"] . "-" . strtolower(preg_replace("/[^a-zA-Z0-9]/", "-", basename($_FILES["userfile"]["name"]))) . "-" . time() . "." . strtolower(end(explode(".", basename($_FILES["userfile"]["name"]))));
					if(move_uploaded_file($_FILES["userfile"]["tmp_name"], "./../uploads/$filename")) {
						echo "<p><strong>Your file was uploaded to <a href=\"../uploads/$filename\">$filename</a> in the uploads directory.</strong></p>";
					}
					else {
						echo "<p>There was a problem moving your file to the target directory.</p>";
					}
				}
				else {
					echo "<p>There was an error with the file you uploaded.</p>";
				}
			}
		}
	}
	else {
		echo "<p><strong>Your uploads directory is not writable. You will not be able to upload files until it is writable.</strong></p>";
	}
?>
<h3>Files I've Uploaded</h3>
	<ul>
		<?php
			$dir = scandir("./../uploads/");
			foreach($dir as $item) {
				if(substr($item, 0, strlen($_SESSION["jara_admin"])) == $_SESSION["jara_admin"]) {
					echo "<li><a href=\"../uploads/$item\" target=\"_blank\">$item</a> - ";
					$name_parts = explode("-", basename($item));
					$time = end($name_parts);
					$time_parts = explode(".", $time);
					$date = $time_parts[0];
					echo date("jS F Y, g:ia", $date);
					echo " - ";
					echo round(filesize("./../uploads/$item")/1024, 2);
					echo "kb";
					echo "</li>";
				}
			}
		?>
	</ul>
<?php
	jara_page_end();
?>